package com.fbt.transfer.app.driver.widget;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.widget.Button;
import android.widget.NumberPicker;
import androidx.annotation.NonNull;
import com.fbt.transfer.app.driver.R;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义年月选择器对话框
 *
 * @author tuocoo
 * @date 2024-11-15
 * @since 1.0.0
 */
public class MonthYearPickerDialog extends Dialog {

    private NumberPicker yearPicker = null;
    private NumberPicker monthPicker = null;
    private Button btnCancel =null;
    private Button btnConfirm = null;
    
    private List<Integer> yearList;
    private String[] monthArray = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"};
    
    private int selectedYear;
    private int selectedMonth;
    
    private OnDateSelectedListener listener = null;
    
    public interface OnDateSelectedListener {
        void onDateSelected(int year, int month);
    }
    
    public MonthYearPickerDialog(@NonNull Context context, int currentYear, int currentMonth) {
        super(context, R.style.DialogStyle);
        initYearList(currentYear);
        this.selectedYear = currentYear;
        this.selectedMonth = currentMonth;
    }
    
    /**
     * 初始化年份列表（当前年份前三年到当前年份）
     */
    private void initYearList(int currentYear) {
        yearList = new ArrayList<>();
        for (int i = currentYear - 3; i <= currentYear; i++) {
            yearList.add(i);
        }
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_month_year_picker);
        
        initViews();
        setupPickers();
        setupListeners();
    }
    
    private void initViews() {
        yearPicker = findViewById(R.id.year_picker);
        monthPicker = findViewById(R.id.month_picker);
        btnCancel = findViewById(R.id.btn_cancel);
        btnConfirm = findViewById(R.id.btn_confirm);
    }
    
    private void setupPickers() {
        // 设置年份选择器
        String[] yearArray = new String[yearList.size()];
        for (int i = 0; i < yearList.size(); i++) {
            yearArray[i] = String.valueOf(yearList.get(i));
        }
        yearPicker.setMinValue(0);
        yearPicker.setMaxValue(yearArray.length - 1); 
        yearPicker.setDisplayedValues(yearArray);
        yearPicker.setWrapSelectorWheel(false);
        
        // 设置当前年份
        int currentYearIndex = yearList.indexOf(selectedYear);
        if (currentYearIndex >= 0) {
            yearPicker.setValue(currentYearIndex);
        }
        
        // 初始化月份选择器基本设置
        monthPicker.setMinValue(0);
        monthPicker.setMaxValue(monthArray.length - 1);
        monthPicker.setWrapSelectorWheel(false);
        
        // 先初始化月份选择器，再设置值
        updateMonthPicker(selectedYear);
        
        // 设置初始月份值（在updateMonthPicker之后）
        int initialMonthIndex = selectedMonth - 1; // 月份从0开始
        if (initialMonthIndex >= 0 && initialMonthIndex < monthPicker.getMaxValue() + 1) {
            monthPicker.setValue(initialMonthIndex);
        }
        
        // 监听年份变化，限制月份选择
        yearPicker.setOnValueChangedListener((picker, oldVal, newVal) -> {
            if (newVal >= 0 && newVal < yearList.size()) {
                int year = yearList.get(newVal);
                updateMonthPicker(year);
            }
        });
    }
    
    /**
     * 根据选择的年份更新月份选择器
     */
    private void updateMonthPicker(int year) {
        LocalDate now = LocalDate.now();
        int currentYear = now.getYear();
        int currentMonth = now.getMonthValue();
        
        // 先清除DisplayedValues避免崩溃
        monthPicker.setDisplayedValues(null);
        
        if (year == currentYear) {
            // 如果是当前年份，只显示到当前月份
            String[] availableMonths = new String[currentMonth];
            System.arraycopy(monthArray, 0, availableMonths, 0, currentMonth);
            
            monthPicker.setMinValue(0);
            monthPicker.setMaxValue(availableMonths.length - 1);
            
            // 如果当前选择的月份超过了可选范围，先调整值再设置DisplayedValues
            int currentValue = monthPicker.getValue();
            if (currentValue >= availableMonths.length) {
                monthPicker.setValue(availableMonths.length - 1);
            }
            
            monthPicker.setDisplayedValues(availableMonths);
        } else {
            // 其他年份显示全部12个月
            monthPicker.setMinValue(0);
            monthPicker.setMaxValue(monthArray.length - 1);
            monthPicker.setDisplayedValues(monthArray);
        }
    }
    
    private void setupListeners() {
        btnCancel.setOnClickListener(v -> dismiss());
        
        btnConfirm.setOnClickListener(v -> {
            int yearIndex = yearPicker.getValue();
            int monthIndex = monthPicker.getValue();
            
            int year = yearList.get(yearIndex);
            int month = monthIndex + 1; // 月份从1开始
            
            if (listener != null) {
                listener.onDateSelected(year, month);
            }
            dismiss();
        });
    }
    
    public void setOnDateSelectedListener(OnDateSelectedListener listener) {
        this.listener = listener;
    }
    
    /**
     * 设置初始选择的年月
     */
    public void setSelectedDate(int year, int month) {
        this.selectedYear = year;
        this.selectedMonth = month;
    }
}